package com.bao.gateway.filter;

import cn.hutool.core.util.StrUtil;
import com.bao.common.adapter.IgnoreTokenConfig;
import com.bao.core.base.R;
import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Value;

public abstract class BaseFilter extends ZuulFilter {
    
    @Value("${server.servlet.context-path}")
    protected String zuulPrefix;
    
    protected boolean isIgnoreToken() {
        HttpServletRequest request = RequestContext.getCurrentContext().getRequest();
        String uri = request.getRequestURI();
        uri = StrUtil.subSuf(uri, zuulPrefix.length());
        uri = StrUtil.subSuf(uri, uri.indexOf("/", 1));
        //判断是否是哪些默认不需要token的uri
        boolean ignoreToken = IgnoreTokenConfig.isIgnoreToken(uri);
        return ignoreToken;
    }
    
    protected void errorResponse(String errMsg, int errCode, int httpStatusCode) {
        R<Object> tokenError = R.fail(errCode, errMsg);
        RequestContext ctx = RequestContext.getCurrentContext();
        //返回错误码
        ctx.setResponseStatusCode(httpStatusCode);
        ctx.addZuulResponseHeader("Context-type", "application/json;charset=UTF-8");
        if (ctx.getResponseBody() == null) {
            //返回错误内容
            ctx.setResponseBody(tokenError.toString());
            //过滤该请求，不对其进行路由
            ctx.setSendZuulResponse(false);
        }
    }
}
